<template>
	<view class="root">
		<view style="padding: 25rpx;height:15vh;">
			<view class="voucher-box" :style="{ background: styleObject.bg }">
				<view class="inviteCode-box">
					<!-- <Icon type='iconweibiaoti-1-02' :color='styleObject.bg'></Icon> -->
					<view class="invite-code flex items-center">
						<view class="flex-1 text-center" :style="{ color: styleObject.color }">
							<view class="invite-title">邀请码</view>
							<view class="code" v-if="shareInfo.invite_code">{{ shareInfo.invite_code }}</view>
						</view>
						<view class="copy-code">
							<view class="copy-btn" @click="onCopy(shareInfo.invite_code)">复制</view>
						</view>
					</view>
				</view>
				<view v-for="(item, index) in 4" :key="index" class="round"></view>
			</view>
		</view>
		<view class="main-body">
			<view class="canvas-box"><canvas class="canvas" canvas-id="canvasId"></canvas></view>
		</view>

		<ul class="channel-body flex ">
			<li @click="onChannel(item.id)" class="flex-1 text-center channel-li" v-for="(item, index) in channel"
				:key="index">
				<view class="img-box"><img class="img" :src="item.img" alt="" /></view>
				<view class="">{{ item.name }}</view>
				<button v-if="item.id == 1" open-type="share" class="share"></button>
			</li>
		</ul>
	</view>
</template>

<script>
	let App = getApp().globalData;
	import Icon from '@/components/Icon/Icon.vue';
	import {
		base64src
	} from '@/utils/base64.js';
	export default {
		components: {
			Icon
		},
		data() {
			return {
				channel: [{
						img: '/static/inviteFriends/4.png',
						id: '0',
						name: '保存此图片'
					},
					{
						img: '/static/inviteFriends/5.png',
						id: '1',
						name: '微信好友'
					}
					// {
					// 	img: '/static/inviteFriends/6.png',
					// 	id: '2',
					// 	name: '微信朋友圈'
					// }
				],
				codePath: '',
				isShareInfo: false,
				img: '',
				shareInfo: {
					share_writer: '推荐好友领福利',
					share_picture: '/static/inviteFriends/3.png',
					share_color: '#ffffff',
					nickname: '',
					avatar: '',
					invite_code: '',
					uid: ''
				},
				appletCode: '', // 小程序码
				base64Avatar: '', // 头像
				styleObject: {
					color: '#fff',
					bg: '#ff626b'
				}
			};
		},
		computed: {
			distributor_id() {
				return this.$store.distributor_id;
			}
		},
		mounted() {
			App.clearDir();
			this.getShareCopy();
			console.log('distributor_id', this.distributor_id);
		},
		methods: {
			onChannel(type) {
				switch (type) {
					case '0':
						console.log('保存');
						this.saveImg();
						break;
					case '1':
						console.log('微信好友');
						break;
					case '2':
						console.log('朋友圈');
						break;
				}
			},

			saveImg() {
				let system_info = uni.getSystemInfoSync();
				let px = uni.upx2px(50);
				let bgw = Number(system_info.windowWidth) - px;
				let bgh = uni.upx2px(800);
				uni.canvasToTempFilePath({
					x: 0,
					y: 0,
					width: bgw,
					height: bgh,
					canvasId: 'canvasId',
					success: function(res) {
						// 在H5平台下，tempFilePath 为 base64
						console.log(res.tempFilePath);
						uni.saveImageToPhotosAlbum({
							filePath: res.tempFilePath,
							success: () => {
								uni.showToast({
									title: '保存成功'
								});
								App.clearDir();
							},
							fail() {
								uni.showToast({
									icon: 'none',
									title: '保存失败'
								});
							}
						});
					},
					fail() {
						uni.showToast({
							icon: 'none',
							title: '图片生成失败'
						});
					}
				});
			},

			async drawCanvas(path) {
				console.log('绘制');
				let bg = this.shareInfo.share_picture;
				// let bg =
				// 	'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1595588716918&di=31c4628c3d4487d15b6ea66a6c2295db&imgtype=0&src=http%3A%2F%2Fimage3.cnpp.cn%2Fupload2%2Fnews%2F20120412%2F161403_49208_url.jpg';
				var ctx = uni.createCanvasContext('canvasId', this);
				let system_info = uni.getSystemInfoSync();
				let px = uni.upx2px(50)
				let bgw = Number(system_info.windowWidth) - px;
				let bgh = uni.upx2px(800);
				// 背景
				let bg2 = '/static/inviteFriends/3.png';

				this.drawRoundRectAvatar(ctx, 0, 0, bgw, bgh, 6, this.img);

				// 头像+小程序码白色背景

				let _contentCenter = parseInt(bgw / 2);
				let wh = 100; // 整个白色背景
				let _contentW = _contentCenter - parseInt(wh / 2);
				let _contentH = bgh - wh - 20;
				console.log('_contentW', _contentW);
				// this._drawRoundRect(ctx, _contentW, _contentH, wh, wh, 6);
				this._drawRoundRect(ctx, _contentW, _contentH, wh, wh, 6);
				// 二维码
				let codeWh = 70;
				let _codeW = _contentCenter - parseInt(codeWh / 2);
				let _codeH = bgh - codeWh - 25;
				ctx.drawImage(this.appletCode, _codeW, _codeH, codeWh, codeWh);
				// 头像
				let acatarBgWh = 50;
				let avatarbgW = _contentCenter - parseInt(acatarBgWh / 2);
				let avatarbgH = _codeH - 45;
				if (this.isShareInfo) {
					// 头像白色背景
					this._drawRoundRect(ctx, avatarbgW, avatarbgH, acatarBgWh, acatarBgWh, 25);
					// 头像

					let avatarW = avatarbgW + 5;
					let avatarH = avatarbgH + 5;
					let acatarWh = 40;
					this.drawRoundRectAvatar(ctx, avatarW, avatarH, acatarWh, acatarWh, 20, this.base64Avatar);
				}

				// 文字
				ctx.setFontSize(28);
				ctx.setTextAlign('center');
				console.log('正则颜色', this.testColor(this.shareInfo.share_color), this.shareInfo.share_color)

				if (this.testColor(this.shareInfo.share_color)) {
					ctx.setFillStyle(this.shareInfo.share_color);
				} else {
					ctx.setFillStyle('#ffffff');
				}
				// this.drawTextInOneLine(ctx, this.shareInfo.share_writer, bgw / 2, 80, bgw);
				// ctx.fillText(this.shareInfo.share_writer, bgw / 2, 80);
				let textL = parseInt(bgw / 2);
				this.drawText(ctx, this.shareInfo.share_writer, textL, 80, 20, bgw - 30)
				ctx.draw();
			},

			// 绘制背景和圆角
			_drawRoundRect(ctx, x, y, w, h, r) {
				ctx.beginPath(); // 开始创建一个路径
				// console.log(x, y, w, h, r, x + r, y + r, r, Math.PI, Math.PI * 1.5);
				// 左上角
				ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5);
				// 右上角
				// console.log(x + w - r);
				ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2);
				// 右下角
				ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5);
				// 左下角
				ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI);
				ctx.closePath(); // 关闭一个路径。
				// ctx.strokeStyle = '#D8D8D8';
				ctx.fillStyle = '#FFFFFF';
				// ctx.stroke()
				ctx.fill(); // 关闭路径之后进行填充
			},

			// 绘制头像
			drawRoundRectAvatar(ctx, x, y, w, h, r, imgPath) {
				ctx.save();
				this._drawRoundRect(ctx, x, y, w, h, r);
				ctx.clip();
				ctx.drawImage(imgPath, x, y, w, h);
				ctx.restore();
			},

			// 文字多出显示省略号
			drawTextInOneLine(ctx, t, x, y, w) {
				const chr = t.split('');
				let temp = '';
				console.log(w, 'measureText', ctx.measureText(temp + '...').width);
				for (let i = 0; i < chr.length; i++) {
					if (ctx.measureText(temp + '...').width <= w) {
						temp += chr[i];
					} else {
						temp = temp.substring(0, temp.length - 1);
						temp += '...';
						break;
					}
				}
				ctx.fillText(temp, x, y);
			},
			/**
			 * 绘制多行文本
			 * @param ctx canvas对象
			 * @param str 文本
			 * @param leftWidth 距离左侧的距离
			 * @param initHeight 距离顶部的距离
			 * @param titleHeight 文本的高度
			 * @param canvasWidth 文本的宽度
			 * @returns {*}
			 */
			drawText: function(ctx, str, leftWidth, initHeight, titleHeight, canvasWidth) {
				let lineWidth = 0;
				let lastSubStrIndex = 0; //每次开始截取的字符串的索引
				for (let i = 0; i < str.length; i++) {
					lineWidth += ctx.measureText(str[i]).width;
					if (lineWidth > canvasWidth) {
						ctx.fillText(str.substring(lastSubStrIndex, i), leftWidth, initHeight); //绘制截取部分
						initHeight += 40; //22为 文字大小20 + 2
						lineWidth = 0;
						lastSubStrIndex = i;
						titleHeight += 40;
					}
					if (i == str.length - 1) { //绘制剩余部分
						ctx.fillText(str.substring(lastSubStrIndex, i + 1), leftWidth, initHeight);
					}
				}
				// 标题border-bottom 线距顶部距离
				titleHeight = titleHeight + 10;
				console.log('titleHeight', titleHeight)
				return titleHeight;
			},
			getImageInfo(url) {
				console.log('getImageInfo -- 获取图片信息', url);
				return new Promise((resolve, reject) => {
					uni.getImageInfo({
						src: url,
						success: function(image) {
							console.log('获取图片信息', image);
							resolve(true);
						},
						fail(err) {
							console.log(err);
							reject(false);
						}
					});
				});
			},
			//
			async downloadImage(url) {
				console.log('downloadImage -- 下载', url);
				let imgInfo = await this.getImageInfo(url).catch(e => {
					console.log('图片设置有误');
					return false;
				});
				console.log('imgInfo', imgInfo);
				if (imgInfo) {
					return new Promise((resolve, reject) => {
						uni.downloadFile({
							url: url,
							success: res => {
								console.log('downloadFile', res);
								resolve(res);
							},
							fail: err => {
								console.log('downloadFile', err);
								App.showToast({
									title: err.errMsg,
									icon: 'none'
								});
								// return reject(err);
							}
						});
					});
				} else {
					console.log('图片设置有误');
				}
			},

			// 获取分享文案
			getShareCopy() {
				let _self = this;
				let p = new Promise((resolve, reject) => {
					this.$request('Distribution/MiniApply/getShareCopy').then(res => {
						if (res.status === 1) {
							let {
								share_writer,
								share_picture,
								share_color,
								nickname,
								avatar,
								uid,
								invite_code,
								invite_under_color,
								invite_code_color
							} = res.data;
							_self.shareInfo['share_writer'] = share_writer;
							_self.shareInfo['share_picture'] = share_picture;
							_self.shareInfo['share_color'] = share_color;
							_self.shareInfo['nickname'] = nickname;
							_self.shareInfo['avatar'] = avatar;
							_self.shareInfo['uid'] = uid;
							_self.shareInfo['invite_code'] = invite_code;
							_self.styleObject['bg'] = invite_under_color;
							_self.styleObject['color'] = invite_code_color;
							_self.isShareInfo = true;
							resolve(res);
						} else {
							_self.isShareInfo = false;
							App.showToast({
								title: res.msg,
								icon: 'none'
							});
						}
					});
				});
				p.then(res => {
					this.getQrcode();
				});
			},

			base64srcImg(img) {
				return new Promise((resolve, reject) => {
					base64src(img, filePath => {
						console.log('filePath - base64Avatar', filePath);
						resolve(filePath);
					});
				});
			},

			getQrcode() {
				console.log('获取小程序码');
				let _self = this;
				let id = this.distributor_id;
				let p = new Promise((resolve, reject) => {
					let obj = {
						image_url: _self.shareInfo['share_picture'],
						path: 'pages/distribution/recruit/recruit?d=' + id,
						avatar_url: _self.shareInfo['avatar']
					};
					this.$request('SmallProgramApi/Share/shareQrCode_v2', obj).then(async res => {
						let qr_code = uni.arrayBufferToBase64(uni.base64ToArrayBuffer(res.data.qr_code));
						let goods_img = uni.arrayBufferToBase64(uni.base64ToArrayBuffer(res.data.goods_img));
						let avatar = uni.arrayBufferToBase64(uni.base64ToArrayBuffer(res.data.avatar_url));

						let code = 'data:image/jpg;base64,' + qr_code;
						let _img = 'data:image/jpg;base64,' + goods_img;
						let avatarImg = 'data:image/jpg;base64,' + avatar;
						_self.img = await this.base64srcImg(_img).catch(err => {
							console.log('_img', err)
						});
						_self.appletCode = await this.base64srcImg(code);
						_self.base64Avatar = await this.base64srcImg(avatarImg);

						resolve();
					});
				});
				p.then(rs => {

					_self.drawCanvas();
				});
			},

			testColor(color) {
				var re1 = /^#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})$/i;
				var re3 =
					/^[rR][gG][Bb][Aa]?[\(]([\s]*(2[0-4][0-9]|25[0-5]|[01]?[0-9][0-9]?),){2}[\s]*(2[0-4][0-9]|25[0-5]|[01]?[0-9][0-9]?),?[\s]*(0\.\d{1,2}|1|0)?[\)]{1}$/g;
				return re1.test(color) || re3.test(color);
			},

			onCopy(code = '智慧零售') {
				uni.setClipboardData({
					data: code,
					success() {
						App.showToast({
							title: '已复制',
							icon: 'none'
						});
					}
				});
			}
		},
		onLoad() {
			console.log('onLoad');
			uni.showShareMenu({
				withShareTicket: true,
				menus: ['shareAppMessage', 'shareTimeline']
			});
		},
		onShareAppMessage(res) {
			let id = this.distributor_id;
			console.log('onShareAppMessage', id);
			// var path = '/pages/distribution/inviteFriends/inviteFriends';
			let path = 'pages/distribution/recruit/recruit?distributor_id=' + id;
			if (res.from == 'button') {}

			return {
				title: this.shareInfo['share_writer'],
				path: path,
				imageUrl: this.shareInfo['share_picture']
			};
		},

		// // 分享朋友圈
		// onShareTimeline: function(res) {
		// 	console.log(res);
		// 	let id = this.distributor_id;
		// 	let path = 'pages/distribution/recruit/recruit?distributor_id=' + id;
		// 	return {
		// 		title: this.shareInfo['share_writer'],
		// 		query: path,
		// 		imageUrl: this.shareInfo['share_picture']
		// 	};
		// }
	};
</script>

<style lang="less">
	@import '@/common/index.less';

	page {
		.bg;
		padding-bottom: 0 !important;
		height: 100vh;
		// overflow: hidden;
	}

	.root {
		height: 100vh;
	}

	.voucher-box {
		// background: #ff626b;
		height: 100%;
		box-sizing: border-box;
		outline: 1px solid #fff;
		outline-offset: -8px;
		position: relative;
		border-radius: 8px;

		&::after,
		&::before {
			content: '';
			display: inline-block;
			position: absolute;
			width: 40rpx;
			height: 40rpx;
			border-radius: 20px;
			// background: linear-gradient(#f6f6f6 20rpx , #f6f6f6 20rpx);
			background: #f6f6f6;
			left: 70%;
		}

		&::after {
			top: -20rpx;
		}

		&::before {
			bottom: -20rpx;
		}

		.round {
			width: 16rpx;
			height: 16rpx;
			color: #fff;
			background: currentColor;
			border-radius: 25px;
			position: absolute;
			left: 72.5%;
			// top: 50%;
			// transform: translate(-50%);
		}

		.round:nth-child(2) {
			top: 30%;
			transform: translate(-30%);
		}

		.round:nth-child(3) {
			top: 40%;
			transform: translate(-30%);
		}

		.round:nth-child(4) {
			top: 50%;
			transform: translate(-30%);
		}

		.round:nth-child(5) {
			top: 60%;
			transform: translate(-30%);
		}
	}


	.main-body {
		// transform: translateY(-70vh);
		overflow: hidden;
		box-sizing: border-box;
		padding: 0 25rpx;
		width: 100%;
		height: calc(85vh - 255rpx);
		margin-bottom: 15rpx;
	
	.info {
			background-color: #7818d1;
			color: #fff;
			padding: 45rpx 25rpx;
			border-radius: 8px;
			margin-bottom: 40rpx;
		}

		.avatar {
			width: 100rpx;
			height: 100rpx;
			margin-right: 10rpx;
		}

		.btn {
			box-sizing: border-box;
			padding: 5rpx 0;
			background: linear-gradient(to right, #febd0b 30%, #fc902b);
			color: #fff;
			border-radius: 25px;
			font-size: 30rpx;
		}

		.qrcodeBg {
			width: 120rpx;
			height: 120rpx;
			background-color: #fff;
		}
	}

	.channel-body {
		box-sizing: border-box;
		padding: 35rpx 0;
		width: 100%;
		height: 190rpx;
		background-color: #fff;
		border-radius: 8px 8px 0 0;
	}

	.channel-li {
		font-size: 28rpx;
		position: relative;
	}

	.share {
		position: absolute;
		top: 0;
		left: 0;
		.wh;
		opacity: 0;
	}

	.img-box {
		width: 80rpx;
		height: 80rpx;
		display: inline-block;
	}

	/***/
	.inviteCode {
		position: relative;
		width: 100%;
		// height: 250rpx;
		height: 20vh;
	}

	.inviteCode-box {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;

		.invite-code {
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;

			.invite-title {
				font-size: 36rpx;
			}

			.code {
				font-size: 50rpx;
			}

			.copy-code {
				width: 200rpx;

				.copy-btn {
					width: 100rpx;
					margin: 0 auto;
					padding: 5rpx 0;
					border-radius: 15px;
					border: 1px solid #fff;
					box-sizing: border-box;
					font-size: 26rpx;
					color: #fff;
					text-align: center;
			}
				}
		}
	}

	.canvas-box {
		width: 100%;
		height: 100%;

		canvas {
			width: 100%;
			height: 100%;
		}
	}
</style>
